<template>
  <div>
    <el-row style="font-size: 24px;">购物车</el-row>
    <el-card>
      <el-row style="text-align: left;"><span style="color: rgb(205,65,60);font-weight: bolder;font-size: 20px;">全部商品 {{totalCount}}</span></el-row>
      <el-table
        ref="tableRef"
        :data="cart.items"
        style="width: 100%"
        row-key="id"
        @selection-change="handleSelectionChange"
        @select="handleSelect"
        @select-all="handleSelectAll"
      >
        <el-table-column
          type="selection"
        >
        </el-table-column>

        <el-table-column
          width="600"
        >
          <template slot-scope="scope">
            <el-row>


            <el-col :span="2">
              <el-image :src="imageServer+'/'+scope.row.skuImage" fit="fit">

              </el-image>
            </el-col>
            <el-col :span="22" style="color: black;">{{scope.row.skuName}}</el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
        >
          <template slot-scope="scope">
             <span style="color: black;text-align: center;">
             ¥{{(scope.row.skuPrice/100).toFixed(2)}}
                </span>
          </template>
        </el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.skuCount"
                             style="width:140px;"
                             size="small"
                             :step="1" step-strictly :min="1"
                             :max="10000"
                             @change="handleSkuCountChange(scope.row)"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
        >
          <template slot-scope="scope">
             <span style="font-weight: bolder;color:black;">
             ¥{{(scope.row.skuPrice*scope.row.skuCount/100).toFixed(2)}}
             </span>
          </template>
        </el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            <span style="cursor: pointer;" @click="handleCartDelete(scope.row)">删除</span>
          </template>

        </el-table-column>
      </el-table>
      <el-row style="padding-top: 20px;color:gray;">
        <el-col :span="2">
          <el-checkbox v-model="allChecked" @change="handleAllChecked">全选</el-checkbox>
        </el-col>
        <el-col :span="4">
          <span style="cursor: pointer;" @click="handleSelectionDelete">删除选中商品</span>
        </el-col>

        <el-col :span="4">
           <span style="cursor: pointer;">
             清理购物车
           </span>

        </el-col>
        <el-col :span="4" style="color: gray;">
          已选 <span style="color:rgb(205,65,60);">{{totalSelectedCount}}</span> 件商品
        </el-col>
        <el-col :span="4" style="color:gray;">
          总价: <span style="color: rgb(205,65,60);font-weight: bolder;"> ¥{{(totalPrice/100).toFixed(2)}}</span>
        </el-col>
        <el-col :span="3" style="float: right;">
          <div style="cursor:pointer;background-color:rgb(205,65,60);font-size: 24px;font-weight: bolder;color:white;height:60px;
                        display:flex;align-items: center;justify-content: center;border-radius: 2px;"
               @click="handlePayment"
          >去结算
          </div>
        </el-col>

      </el-row>
    </el-card>

  </div>
</template>

<script>
  import Vue from 'vue'
  import {mapState} from 'vuex'

  export default {
    name: "Cart",
    data() {
      return {
        selection: [],
        allChecked: false
      }
    },

    computed: {
      ...mapState({
        cart: state => state.auth.cart,
        imageServer: state=>state.prod.imageServer
      }),

      totalPrice() {
        let p = 0;
        this.selection.forEach(v => {
          p += v.skuPrice * v.skuCount;
        })
        return p;
      },

      totalSelectedCount() {
        let c = 0;
        this.selection.forEach(v => {
          c += v.skuCount;
        })
        return c;
      },

      totalCount(){
        let c = 0 ;
        if(!this.cart.items){
          return 0;
        }
        this.cart.items.forEach(v=>c += v.skuCount)
        return c;
      }
    },

    created() {
      console.log("cart created")
      if(this.cart.items) {
        this.$nextTick(() => {
          console.log("this.cart="+JSON.stringify(this.cart));
          this.cart.items.forEach(row => this.$refs.tableRef.toggleRowSelection(row, row.selected == 1));
        })
      }
    },

    watch: {
      cart(newValue, oldValue) {
        console.log("watch cart")
        this.$nextTick(() => {
          console.log("cart=" + JSON.stringify(this.cart));
          newValue.items.forEach(row => this.$refs.tableRef.toggleRowSelection(row, row.selected == 1));
        })

      }
    },

    methods: {

      handleCartDelete(row) {
        this.api.__api__CartUpdate(this.cart.id, row.skuId, 0)
          .then(data => {
            this.$store.commit('setCart', data.data);
            this.$nextTick(() => {
              this.cart.items.forEach(row => this.$refs.tableRef.toggleRowSelection(row, row.selected == 1));
            })
          }).catch(error => null)
      },

      handleSkuCountChange(row) {
        this.api.__api__CartUpdate(this.cart.id, row.skuId, row.skuCount)
          .then(data => {
            this.$store.commit('setCart', data.data);
            this.$nextTick(() => {
              this.cart.items.forEach(row => this.$refs.tableRef.toggleRowSelection(row, row.selected == 1));
            })
          }).catch(error => null)
      },

      handleSelect(selection, row) {
        const cartItemIds = [];
        selection.forEach(v => cartItemIds.push(v.id));
        this.api.__api__CartItemsSelectionUpdate(this.cart.id, cartItemIds)
          .then(data => {
            this.$store.commit('setCart', data.data);
            this.$nextTick(() => {
              this.cart.items.forEach(row => this.$refs.tableRef.toggleRowSelection(row, row.selected == 1));
            })
          })
      },

      handleSelectAll(selection) {
        const cartItemIds = [];
        selection.forEach(v => cartItemIds.push(v.id));
        this.api.__api__CartItemsSelectionUpdate(this.cart.id, cartItemIds)
          .then(data => {
            this.$store.commit('setCart', data.data);
            this.$nextTick(() => {
              this.cart.items.forEach(row => this.$refs.tableRef.toggleRowSelection(row, row.selected == 1));
            })
          })
      },

      handleSelectionChange(selection) {
        Vue.set(this, 'selection', selection);
      },

      handleSelectionDelete() {
        if (!this.selection || this.selection.length == 0) {
          this.$message.info("没有选中商品");
          return;
        }
        const itemIds = [];
        this.selection.forEach(v => itemIds.push(v.id));
        this.api.__api__CartItemsDelete(this.cart.id, itemIds)
          .then(data => {
            this.$store.commit('setCart', data.data);
            this.$nextTick(() => {
              this.cart.items.forEach(row => this.$refs.tableRef.toggleRowSelection(row, row.selected == 1));
            })
          }).catch(error => null)
      },

      handleAllChecked(newValue) {
        const cartItemIds = [];
        if (newValue) {
          this.cart.items.forEach(v => cartItemIds.push(v.id));
        }
        this.api.__api__CartItemsSelectionUpdate(this.cart.id, cartItemIds)
          .then(data => {
            this.$store.commit('setCart', data.data);
            this.$nextTick(() => {
              this.cart.items.forEach(row => this.$refs.tableRef.toggleRowSelection(row, row.selected == 1));
            })
          })
      },

      handlePayment(){
        this.$router.push("/order/creating").catch(error=>null);
      }

    }
  }
</script>

<style scoped>

</style>
